package com.renli.service.impl;


import com.renli.bean.ResultJson;
import com.renli.mapper.LoginMapper;
import com.renli.mapper.UserMapper;
import com.renli.pojo.Login;
import com.renli.pojo.User;
import com.renli.service.LoginService;
import com.renli.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Login findByName(String username) {
        return loginMapper.selectByName(username);
    }

    @Override
    public int add(Login login) {
        return loginMapper.insert(login);
    }


    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean saveToken(String name, String token) {
        System.out.println(name + "==>" + token);
        return redisUtil.set(name, token, 60 * 30);//30分钟
    }

    /**
     * 用户登录
     *
     * @param login
     * @return
     */
    @Override
    public User login(Login login) {

        return userMapper.findByLogin(login);
    }

    @Override
    public ResultJson checkPassword(Map<String, String> map) {

        if (loginMapper.selectByUserIdAndPassword(map) != null) {
            //验证密码成功
            return new ResultJson().setSuccess("验证成功", "1");
        } else {
            return new ResultJson().setSuccess("验证失败", "0");
        }

    }


    /**
     * 验证token  存在于数据库不  存在 重置 token时效
     * 不存在返回null
     *
     * @param name
     * @return
     */
    @Override
    public String checkToken(String name) {
        if (redisUtil.hasKey(name)) {
            //重新 设置为  30分钟;
            redisUtil.expire(name, 30 * 60);
            return (String) redisUtil.get(name);
        }
        return null;
    }

    public Login getLogin(String name) {
        return loginMapper.selectByName(name);
    }

    public ResultJson checkName(String name) {
        System.out.println("checkName==>" + name);
        Login login = loginMapper.selectByName(name);

        if (login != null) {
            return new ResultJson<>().setFail("账号已存在");
        } else {
            return new ResultJson<>().setSuccess("用户可用");
        }

    }


}
